<template>
  <!-- 卡片 -->
  <el-card shadow="hover">
    <el-button type="primary" @click="addTrademark">添加品牌</el-button>
    <el-button type="primary">导出此页数据</el-button>
    <!-- 表格 -->
    <el-table :data="trademarkList" border style="margin:20px 0 ;" >
      <el-table-column label="序号" width="80" type="index" align="center"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌logo">
        <!-- 匿名作用域插槽 -->
        <template #="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width:100px;height:100px;">
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, $index }">
          <el-button type="primary" :icon="Edit" @click="updateTrademark(row)"></el-button>
          <el-button type="danger" :icon="Delete"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 100]"
      :size="'large'" background layout="total, prev, pager, next, jumper,->, sizes" :total="total"
      @size-change="pageSizeHandler" @current-change="currentHandler" />

    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkInfo.id ? '修改品牌' : '添加品牌'" >
      <el-form :label-width="100" style="width:80%" :model="trademarkInfo" :rules="rules" ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="trademarkInfo.tmName" />
        </el-form-item >
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 上传 
          action:上传图片的请求地址 上传图片post 需要代理跨域 app-dev ，返回图片网络地址
          show-file-list:显示上传文件的名字
          before-upload:在上传之前的回调
          on-success上传请求成功的回调
        -->
          <el-upload class="avatar-uploader" action="/app-dev/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <!-- 插槽：图片或加号二选一 -->
            <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import { reqTrademarkList, reqUpdateOrAddTrademark } from '@/api/product/trademark'
import type { TrademarkResponseData, TrademarkList, Trademark } from '@/api/product/type/trademark'
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
// 当前页
let pageNo = ref<number>(1)
// 每页条数
let pageSize = ref<number>(3)
//品牌列表
let trademarkList = ref<TrademarkList>([])
//总条数
let total = ref<number>(1)
//对话表单是否可见
let dialogFormVisible = ref<boolean>(false)

//对话表单数据：品牌数据
let trademarkInfo = reactive<Trademark>({
  tmName: '',
  logoUrl: ''
})

//获取表单实例
const formRef = ref<any>()

//获取品牌列表
const getTrademarkList = async () => {
  const result: TrademarkResponseData = await reqTrademarkList(pageNo.value, pageSize.value)
  trademarkList.value = result.records
  total.value = result.total
}
//修改当前页，发送请求
const currentHandler = (current: number) => {
  pageNo.value = current
  getTrademarkList()
}
//修改每页条数，发送请求
const pageSizeHandler = (size: number) => {
  //先要重置第一页
  pageNo.value = 1
  pageSize.value = size
  getTrademarkList()
}

//打开对话框
const addTrademark = () => {
  //重置表单内容:也会触发校验，清除校验结果还是有啊，改校验触发方式blue
  reset()
  dialogFormVisible.value = true
  //清楚表单校验结果
  clearFormFieldResult()
}

//上传图片前
const beforeAvatarUpload = (rawFile: any) => {
  // console.log(rawFile)
  if (rawFile.type === 'image/png' || rawFile.type === 'image/jpeg' || rawFile.type === 'image/gif') {
    //图片小于2M
    if (rawFile.size / 1024 / 1024 < 2) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传大小超过2M'
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传类型有误'
    })
    return false
  }

}

//上传成功
const handleAvatarSuccess = (response:any) => {
  // console.log(response)
  //添加网络地址
  trademarkInfo.logoUrl =  response.data
  //清空校验结果
  formRef.value.clearValidate('logoUrl')
}
//对话框确认
const confirm = async () => {
  try {
    //整体校验
    await formRef.value.validate()
    //发请求：添加或修改品牌
    await reqUpdateOrAddTrademark(trademarkInfo) 
    ElMessage({
      type:'success',
      message:trademarkInfo.id ? '修改品牌成功' :'添加品牌成功' 
    })
    //关闭对话框
    dialogFormVisible.value = false
    //重新获取列表:如果有id，留在当前页
    // pageNo.value = trademarkInfo.id ? pageNo.value : 1
    !trademarkInfo.id && (pageNo.value = 1)
    getTrademarkList()
  } catch (error) {
    //什么都不做
    ElMessage({
      type:'error',
      message:trademarkInfo.id ? '修改品牌失败':'添加品牌失败'
    })
  }

}
//对话框重置
const reset = () => {
  trademarkInfo.id = 0
  trademarkInfo.logoUrl = ''
  trademarkInfo.tmName = ''
}

//自定义规则
const validatorTmName = (rule:any,value:any,callBack:any) => {
  if(/^[\u4e00-\u9fa5]{2,}$/.test(value)) {
    callBack()
  } else {
    callBack(new Error('请输入至少2位的汉字'))
  }
}
//上传文件无法通过change或blue触发，只能通过整体校验触发
const validatorLogoUrl = (rule:any,value:any,callBack:any) => {
  //value是返回的图片的网络地址，没有返回就是null
  // console.log(value)
  if (value) {
    callBack()
  } else {
    callBack(new Error('请添加图片'))
  }
}

//表单校验规则
const rules = {
  // 内置校验和自定义校验
  tmName:[
  // {
  //   required: true,min:2,max:5, message: '品牌名在2-5位', trigger: 'change'
  // }
  {
    required:true,trigger:'blue',validator:validatorTmName
  }
],
  logoUrl:[
    {required:true,validator:validatorLogoUrl}
  ]
}
//清空表单校验结果
const clearFormFieldResult = () => {
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
}

//更新品牌
const updateTrademark = (row:Trademark) => {
  //修改表单数据
  trademarkInfo.id = row.id
  trademarkInfo.tmName = row.tmName
  trademarkInfo.logoUrl = row.logoUrl
  //打开对话框
  dialogFormVisible.value = true
}
onMounted(() => {
  getTrademarkList()
})
</script>

<style>
.el-dialog {
  margin-top: 100px;
}
</style>
<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>